//
//  UserCenter.swift
//  MT
//
//  Created by M on 2019/12/21.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import ObjectMapper

import RxSwift
import RxDataSources
import Moya
import Result

class UserCenter: NSObject {
    
    /// MTProvider
    private lazy var provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    ///
    static let `default`: UserCenter = UserCenter()
    
    var imgList: [UserMediaListModel]?
    
    var age: Int?
    /// 地区
    var area: String?
    
    /// 女性审核视频 ID
    var auditVedioId: Int?
    
    /// 生日
    var birthday: String?
    
    /// 市
    var city: String?
    
    /// 创建日期
    var createTime: String?
    
    /// 礼物金额
    var giftPrice: Int?
    
    /// 头像id
    var headImgId: Int?
    
    /// 主键 Id
    var id: Int?
    
    /// 最后一次心跳时间
    var lastHeartTime: String?
    
    /// 钻石
    var money: Int?
    
    /// 点券
    var ticketAmount: Int?
    
    /// 名称
    var nickname: String?
    
    /// 在线状态 1：离线；2：在线
    var onlineStatus: Int?
    
    /// 省份
    var province: String?
    
    /// 性别 0：男；1：女
    var sex: Int?
    
    /// 更新时间
    var updateTime: String?
    
    /// 登录账号
    var userName: String?
    
    /// 密码
    var userPassword: String?
    
    /// 用户状态 0：审核中，1：审核通过，2：黑名单，4： 审核失败，11：已上传初始化资料，12：已上传视频审核
    var userStatus: Int?
    
    /// 授权信息
    var auth: UserAuthInfo?
    
    /// 广场Id
    var roomId: Int?
    
    /// 用户头像
    var headerUrl: String?
    
    /// 认证类型
    var vipType: Int?
    
    /// 认证状态
    var vipState: Int?
    /// 标签列表
    //var tagList: [UserTagList]?
    /// hobbyList
    var hobbyList: [String]?
    
    var likeCount: Int?
    var friendsCount: Int?
    var selfLike: Bool?
    var levelId: Int?
    var levelName: String?
    
    var school: String?
    /// 客服账号
    var customerUserName: String?
}

extension UserCenter {
    
    public func set(with dict: [String: Any]) {
        self.likeCount          = dict["likeCount"] as? Int
        customerUserName        = dict["customerUserName"] as? String
        self.friendsCount          = dict["friendsCount"] as? Int
        self.selfLike           = dict["selfLike"] as? Bool
        self.levelId            = dict["levelId"] as? Int
        self.levelName          = dict["levelName"] as? String
        self.hobbyList          = dict["hobbyList"] as? [String]
        self.age                = dict["age"] as? Int
        self.vipState           = dict["vipState"] as? Int
        self.vipType            = dict["vipType"] as? Int
        self.headerUrl          = dict["headerUrl"] as? String
        self.area               = dict["area"] as? String
        self.auditVedioId       = dict["auditVedioId"] as? Int
        self.birthday           = dict["birthday"] as? String
        self.city               = dict["city"] as? String
        self.createTime         = dict["createTime"] as? String
        self.giftPrice          = dict["giftPrice"] as? Int
        self.headImgId          = dict["headImgId"] as? Int
        self.id                 = dict["id"] as? Int
        self.lastHeartTime      = dict["lastHeartTime"] as? String
        self.money              = dict["money"] as? Int
        self.ticketAmount       = dict["ticketAmount"] as? Int
        self.nickname           = dict["nickname"] as? String
        self.onlineStatus       = dict["onlineStatus"] as? Int
        self.province           = dict["province"] as? String
        self.sex                = dict["sex"] as? Int
        self.updateTime         = dict["updateTime"] as? String
        self.userName           = dict["userName"] as? String
        self.userPassword       = dict["userPassword"] as? String
        self.userStatus         = dict["userStatus"] as? Int
        self.imgList            = dict["imgList"] as? [UserMediaListModel]
        if let roomId = dict["roomId"] as? Int {
            self.roomId         = roomId
        }
        if let auth = dict["auth"] as? [String: Any] {
            self.auth = UserAuthInfo(dict: auth)
        }
        
//        if let tagList = dict["tagList"] as? [[String : Any]] {
//            var lis: [UserTagList] = []
//            for (_, v) in tagList.enumerated() {
//                let t = UserTagList(dict: v)
//                lis.append(t)
//            }
//            self.tagList = lis
//        }
        
        // userDefault
        UserDefaults.MTUserCenter.area.store(value: self.area)
        UserDefaults.MTUserCenter.auditVedioId.store(value: self.auditVedioId)
        UserDefaults.MTUserCenter.birthday.store(value: self.birthday)
        UserDefaults.MTUserCenter.city.store(value: self.city)
        UserDefaults.MTUserCenter.createTime.store(value: self.createTime)
        UserDefaults.MTUserCenter.giftPrice.store(value: self.giftPrice)
        UserDefaults.MTUserCenter.headImgId.store(value: self.headImgId)
        UserDefaults.MTUserCenter.id.store(value: self.id)
        UserDefaults.MTUserCenter.lastHeartTime.store(value: self.lastHeartTime)
        UserDefaults.MTUserCenter.money.store(value: self.money)
        UserDefaults.MTUserCenter.ticketAmount.store(value: self.ticketAmount)
        UserDefaults.MTUserCenter.nickname.store(value: self.nickname)
        UserDefaults.MTUserCenter.onlineStatus.store(value: self.onlineStatus)
        UserDefaults.MTUserCenter.province.store(value: self.province)
        UserDefaults.MTUserCenter.sex.store(value: self.sex)
        UserDefaults.MTUserCenter.updateTime.store(value: self.updateTime)
        UserDefaults.MTUserCenter.userName.store(value: self.userName)
        UserDefaults.MTUserCenter.userPassword.store(value: self.userPassword)
        UserDefaults.MTUserCenter.userStatus.store(value: self.userStatus)
        UserDefaults.MTUserCenter.token.store(value: self.auth?.token)
        UserDefaults.MTUserCenter.refreshToken.store(value: self.auth?.refreshToken)
        UserDefaults.MTUserCenter.age.store(value: self.age)
        
        UserDefaults.MTUserCenter.likeCount.store(value: self.likeCount)
        UserDefaults.MTUserCenter.friendsCount.store(value: self.friendsCount)
        UserDefaults.MTUserCenter.selfLike.store(value: self.selfLike)
        UserDefaults.MTUserCenter.levelId.store(value: self.levelId)
        UserDefaults.MTUserCenter.levelName.store(value: self.levelName)
        UserDefaults.MTUserCenter.hobbyList.store(value: self.hobbyList)
        UserDefaults.MTUserCenter.vipState.store(value: self.vipState)
        UserDefaults.MTUserCenter.vipType.store(value: self.vipType)
        UserDefaults.MTUserCenter.headerUrl.store(value: self.headerUrl)
        UserDefaults.MTUserCenter.imgList.store(value: self.imgList)
        UserDefaults.MTUserCenter.customerUserName.store(value: self.customerUserName)
        
        if let roomId = self.roomId {
            UserDefaults.MTUserCenter.roomId.store(value: roomId)
        }
        
    }
    
    public func setValueFromStoredValue() {
        self.customerUserName   = UserDefaults.MTUserCenter.customerUserName.storedValue as? String
        self.imgList            = UserDefaults.MTUserCenter.imgList.storedValue as? [UserMediaListModel]
        self.area               = UserDefaults.MTUserCenter.area.storedString
        self.auditVedioId       = UserDefaults.MTUserCenter.auditVedioId.storedInt
        self.birthday           = UserDefaults.MTUserCenter.birthday.storedString
        self.city               = UserDefaults.MTUserCenter.city.storedString
        self.createTime         = UserDefaults.MTUserCenter.createTime.storedString
        self.giftPrice          = UserDefaults.MTUserCenter.giftPrice.storedInt
        self.headImgId          = UserDefaults.MTUserCenter.headImgId.storedInt
        self.id                 = UserDefaults.MTUserCenter.id.storedInt
        self.lastHeartTime      = UserDefaults.MTUserCenter.lastHeartTime.storedString
        self.money              = UserDefaults.MTUserCenter.money.storedInt
        self.ticketAmount       = UserDefaults.MTUserCenter.ticketAmount.storedInt
        self.nickname           = UserDefaults.MTUserCenter.nickname.storedString
        self.onlineStatus       = UserDefaults.MTUserCenter.onlineStatus.storedInt
        self.province           = UserDefaults.MTUserCenter.province.storedString
        self.sex                = UserDefaults.MTUserCenter.sex.storedInt
        self.updateTime         = UserDefaults.MTUserCenter.updateTime.storedString
        self.userName           = UserDefaults.MTUserCenter.userName.storedString
        self.userPassword       = UserDefaults.MTUserCenter.userPassword.storedString
        self.userStatus         = UserDefaults.MTUserCenter.userStatus.storedInt
        self.roomId             = UserDefaults.MTUserCenter.roomId.storedInt
        self.age                = UserDefaults.MTUserCenter.age.storedInt
        self.likeCount          = UserDefaults.MTUserCenter.likeCount.storedInt
        self.friendsCount       = UserDefaults.MTUserCenter.friendsCount.storedInt
        self.selfLike           = UserDefaults.MTUserCenter.selfLike.storedBool
        self.levelId            = UserDefaults.MTUserCenter.levelId.storedInt
        self.levelName          = UserDefaults.MTUserCenter.levelName.storedString
        self.hobbyList          = UserDefaults.MTUserCenter.hobbyList.storedValue as? [String]
        self.vipState           = UserDefaults.MTUserCenter.vipState.storedInt
        self.vipType            = UserDefaults.MTUserCenter.vipType.storedInt
        self.headerUrl          = UserDefaults.MTUserCenter.headerUrl.storedString
        
        let auth = UserAuthInfo()
        auth.token              = UserDefaults.MTUserCenter.token.storedString
        auth.refreshToken       = UserDefaults.MTUserCenter.refreshToken.storedString
        self.auth               = auth
        
        //let tagList = UserTagList()
        //tagList.id =
//        self.tagList = tagList
    }
    
    public func clear() {
        self.area               = nil
        self.auditVedioId       = nil
        self.birthday           = nil
        self.city               = nil
        self.createTime         = nil
        self.giftPrice          = nil
        self.headImgId          = nil
        self.id                 = nil
        self.lastHeartTime      = nil
        self.money              = nil
        self.ticketAmount       = nil
        self.nickname           = nil
        self.onlineStatus       = nil
        self.province           = nil
        self.sex                = nil
        self.updateTime         = nil
        self.userName           = nil
        self.userPassword       = nil
        self.userStatus         = nil
        self.roomId             = nil
        self.auth               = nil
        self.age               = nil
        self.likeCount          = nil
        self.friendsCount       = nil
        self.selfLike           = nil
        self.levelId            = nil
        self.levelName          = nil
        self.hobbyList          = nil
        self.vipState           = nil
        self.vipType            = nil
        self.headerUrl          = nil
        self.imgList            = nil
        self.customerUserName   = nil
        
        UserDefaults.MTUserCenter.area.store(value: nil)
        UserDefaults.MTUserCenter.auditVedioId.store(value: nil)
        UserDefaults.MTUserCenter.birthday.store(value: nil)
        UserDefaults.MTUserCenter.city.store(value: nil)
        UserDefaults.MTUserCenter.createTime.store(value: nil)
        UserDefaults.MTUserCenter.giftPrice.store(value: nil)
        UserDefaults.MTUserCenter.headImgId.store(value: nil)
        UserDefaults.MTUserCenter.id.store(value: nil)
        UserDefaults.MTUserCenter.lastHeartTime.store(value: nil)
        UserDefaults.MTUserCenter.money.store(value: nil)
        UserDefaults.MTUserCenter.ticketAmount.store(value: nil)
        UserDefaults.MTUserCenter.nickname.store(value: nil)
        UserDefaults.MTUserCenter.onlineStatus.store(value: nil)
        UserDefaults.MTUserCenter.province.store(value: nil)
        UserDefaults.MTUserCenter.sex.store(value: nil)
        UserDefaults.MTUserCenter.updateTime.store(value: nil)
        UserDefaults.MTUserCenter.userName.store(value: nil)
        UserDefaults.MTUserCenter.userPassword.store(value: nil)
        UserDefaults.MTUserCenter.userStatus.store(value: nil)
        UserDefaults.MTUserCenter.token.store(value: nil)
        UserDefaults.MTUserCenter.refreshToken.store(value: nil)
        UserDefaults.MTUserCenter.roomId.store(value: nil)
        UserDefaults.MTUserCenter.likeCount.store(value: nil)
        UserDefaults.MTUserCenter.friendsCount.store(value: nil)
        UserDefaults.MTUserCenter.selfLike.store(value: nil)
        UserDefaults.MTUserCenter.levelId.store(value: nil)
        UserDefaults.MTUserCenter.levelName.store(value: nil)
        UserDefaults.MTUserCenter.hobbyList.store(value: nil)
        UserDefaults.MTUserCenter.vipState.store(value: nil)
        UserDefaults.MTUserCenter.vipType.store(value: nil)
        UserDefaults.MTUserCenter.headerUrl.store(value: nil)
        UserDefaults.MTUserCenter.age.store(value: nil)
        UserDefaults.AppValidate.isConfirmUserAgreement.store(value: false)
        UserDefaults.MTUserCenter.imgList.store(value: nil)
        UserDefaults.MTUserCenter.customerUserName.store(value: nil)
    }
    
    public func logout(completion: (() -> Swift.Void)? = nil) {
        KeychainItem.currentUserIdentifier = nil
        KeychainItem.currentUserFirstName = nil
        KeychainItem.currentUserLastName = nil
        KeychainItem.currentUserEmail = nil
        clear()
        IMLoginManager.logout()
        DispatchQueue.main.async {
            let vc = MTLoginViewController()
            let nav = BaseNavController(rootViewController: vc)
            UIApplication.mt_keyWindow?.rootViewController = nav
            if let completion = completion {
                completion()
            }
        }
    }
    
    /// 更新用户信息
    public func updateInfos(completion: ((_ flag: Bool) -> Swift.Void)? = nil) {
        guard let id = id else {
            return
        }
        provider.originRequest(.update(id), callbackQueue: nil, progress: nil) { [weak self] (result, _) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
                    if let result = datas["result"] as? [String: Any] {
                        weakself.set(with: result)
                        debugPrint("lkadsjflsjfkljsdklfakldsfjlksadflasdfjks")
                    }
                }
                break
            case .failure(_):
                break
            }
        }
        
    }

}

class UserAuthInfo: NSObject {
    
    /// refreshToken
    @objc public var refreshToken: String?
    
    /// access - token
    @objc public var token: String?
    
    override init() {
        super.init()
    }
    
    convenience init(dict: [String: Any]) {
        self.init()
        setValuesForKeys(dict)
    }
    
}

class UserTagList: NSObject {
    
    /// refreshToken
    public var id: Int?
    // 1系统标签，2自定义标签
    public var isSystem: Int?
    public var name: Int?
    // 1 个性标签，2兴趣爱好
    public var tagType: Int?
    // 是否关联，1已经选中，0未选中
    public var tagged: Int?
    // 用户ID
    public var userId: Int?
    
    override init() {
        super.init()
    }
    
    convenience init(dict: [String: Any]) {
        self.init()
        setValuesForKeys(dict)
    }
    
}

/// 接口环境配置
public extension UserDefaults {
    
    enum  MTUserCenter: String, UserDefaultSettable {
        
        case imgList
        case likeCount
        case friendsCount
        case selfLike
        case levelId
        case levelName
        case hobbyList
        case tagList
        case vipState
        case vipType
        case headerUrl
        case age
        /// 客服账号
        case customerUserName
        /// 区域
        case area
            
        /// 女性审核视频 ID
        case auditVedioId
        
        /// 生日
        case birthday
        
        /// 市
        case city
        
        /// 创建日期
        case createTime
        
        /// 礼物金额
        case giftPrice
        
        /// 头像id
        case headImgId
        
        /// 主键 Id
        case id
        
        /// 最后一次心跳时间
        case lastHeartTime
        
        /// 点券 - 不能用来购买 - 只能用来提现
        case money
        
        /// 钻石
        case ticketAmount
        
        /// 名称
        case nickname
        
        /// 在线状态 1：离线；2：在线
        case onlineStatus
        
        /// 省份
        case province
        
        /// 性别 0：男；1：女
        case sex
        
        /// 更新时间
        case updateTime
        
        /// 登录账号
        case userName
        
        /// 密码
        case userPassword
        
        /// 用户状态；0：审核中；1：审核通过；2：黑名单
        case userStatus
        
        /// access-token
        case token
        
        ///
        case refreshToken
        
        ///
        case roomId
        
    }
    
}


// MARK: - 查询用户余额模型
class MTUserMoneyModel: Mappable {
    /// 请求是否成功的code
    var code: Int?
    /// 请求返回的Message
    var message: String?
    /// 分页对象
    var page: PageModel?
    /// 时间戳
    var timestamp: TimeInterval?
    
    var result: Int?
    
    required public init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        code            <- map["code"]
        message         <- map["message"]
        page            <- map["page"]
        timestamp       <- map["timestamp"]
        result          <- map["result"]
    }
    
}
